var ajaxLocker = false;
var DEFAULT_PAGE_HANDLER = 'onPageChange';

//  Bootbox
function getConfirm(message, callback) {
    return {
        message: message,
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn-outline btn-circle green-meadow'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn-outline btn-circle blue'
            }
        },
        callback: function(result) {
            if (result) {
                callback();
            }
        }
    };
}

//  Switch
function getMiniStatusSwitch(callback) {
    return {
        size: "mini",
        onText: "启用",
        offText: "禁用",
        onColor: "success",
        offColor: "danger",
        animate: false,
        onSwitchChange: function(event, state) {
           callback(event, state);
        }
    };
}

function getNormalStatusSwitch(callback) {
    return {
        size: "normal",
        onText: "<i class='fa fa-check' style='margin-right: 3px;'></i>启用",
        offText: "<i class='fa fa-ban' style='margin-right: 3px;'></i>禁用",
        onColor: "success",
        offColor: "danger",
        animate: true,
        onSwitchChange: function(event, state) {
            callback(event, state);
        }
    };
}

//  Tab methods
function openTab(activeTab, tabHeaderMessage, remoteUrl) {
    showTab(activeTab, tabHeaderMessage);
    $("[data-category='tab'][data-tab='" + activeTab + "']").load(remoteUrl);
}

function closeTab() {
    var activeTabNav = $('[data-category="tabNav"] .active');
    activeTabNav.addClass('hide');
    var pane = activeTabNav.children("a").data("tab-nav");
    $('[data-tab="' + pane + '"]').html("");
    showTab('list', '列表');
}

function showTab(activeTab, tabHeaderMessage) {
    $("[data-category='tabNav'] li").removeClass("active");
    $("[data-tab-nav='" + activeTab + "']").text(tabHeaderMessage).parent().removeClass('hide').addClass("active");

    $("[data-category='tab']").removeClass("active");
    $("[data-category='tab'][data-tab='" + activeTab + "']").addClass("active");
}

//  Ajax methods
function ajaxLoad(data, url, divId) {
    $.ajax({
        url: url,
        method: "GET",
        data: data,
        success: function(result) {
            $("#" + divId).html(result);
        }
    });
}

/**
 * Ajax Json Post请求，返回之后用Bootbox通知用户
 * @param url
 * @param data
 * @param successMessage
 * @param errorMessage
 */
function ajaxExecuteWithJson(url, data, successMessage, errorMessage) {
    ajaxPostWithJson(url, data,
        function(baseModel) {
            if (baseModel.hasError) {
                bootbox.alert(successMessage);
            }
        },
        function() {
            bootbox.alert(errorMessage);
        }
    );
}

function ajaxPostWithJson(url, data, successCallback, errorCallback, alwaysCallback) {
    if (ajaxLocker) {
        return;
    }

    ajaxLocker = true;

    $.ajax({
        url: url,
        method: 'POST',
        contentType: 'application/json;charset=utf-8',
        data: JSON.stringify(data),
        success: function(response) {
            if (successCallback) {
                successCallback(response);
            }
        },
        error: function() {
            if (errorCallback) {
                errorCallback();
            }
        }
    }).always(function() {
        ajaxLocker = false;
        if (alwaysCallback) {
            alwaysCallback();
        }
    });
}

//  Server error message
function showServerErrorMessage(message) {
    $('[data-category="errorMessage"]').removeClass("display-hide");
    $('[data-category="errorMessage"]').css("display", "block");
    $('[data-category="serverErrorMessage"]').html('<label class="error">' + message + '</label>');
}

/**
 * 获得某个分页控件的当前页数
 * @param handlerName
 * @returns {Number}
 */
function getCurrentPageNumber(handlerName) {
    if (handlerName) {
        return parseInt($("[data-page-handler=" + handlerName + "] a.blue").text());
    }
    return  parseInt($("[data-page-handler=" + DEFAULT_PAGE_HANDLER + "] a.blue").text());
}

/**
 * 表单验证
 */
function createValidation(formId, errorContainer) {
    var v = $(formId).validate({
        errorContainer: errorContainer,
        highlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error').addClass('has-error');
        },
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        errorPlacement: function(error) {
            $('[data-category="serverErrorMessage"]').html("");
            $(errorContainer).append(error);
        }
    });

    var remoteSelector = formId + ' input[x-data-flag-remote="true"]';
    $(remoteSelector).each(function() {
        var elementId = $(this).attr("id");
        $(this).rules("add", {
            remote: {
                url: $(this).attr("x-data-rule-remote"),
                type: "post",
                async: false,           // ！设置为同步
                data: {
                    data: function() { return $('#' + elementId).val() },
                    id: function() { return $('#' + elementId).attr('x-data-id') ? $('#' + elementId).attr('x-data-id') : '' }
                },
                dataFilter: function(result) {
                    if (result == "success") {
                        $('#' + elementId).parent().parent().removeClass('has-error');
                        return true;
                    }
                    return false;
                }
            },
            messages: {
                remote: $(this).attr("x-data-msg-remote")
            }
        });
    });
}
